package com.controller.machine;

import com.common.ErrorCodeEnum;
import com.common.anntation.Log;
import com.common.emums.BusinessType;
import com.common.excel.ExcelUtil;
import com.common.exception.BusinessException;
import com.common.utils.*;
import com.core.springSecurity.common.SecurityUtils;
import com.core.springSecurity.model.LoginUserDetails;
import com.github.pagehelper.PageInfo;
import com.model.base.PageResult;
import com.model.base.Result;
import com.model.domain.machine.GetMachineBindDeviceRecordInfoDO;
import com.model.domain.machine.GetMachineInfoDO;
import com.model.domain.user.GetUserInfoDO;
import com.model.dto.dealer.dealerInfo.GetDealerListDTO;
import com.model.dto.dealer.dealerInfo.SaveDealerInfoDTO;
import com.model.dto.machine.machineInfo.*;
import com.model.pojo.dealer.DealerInfo;
import com.model.pojo.device.DeviceObdBaseInfo;
import com.model.pojo.device.DevicePmdBaseInfo;
import com.model.pojo.machine.MachineBindDeviceRecordInfo;
import com.model.pojo.machine.MachineInfo;
import com.model.pojo.owner.OwnerInfo;
import com.model.pojo.sys.SysUser;
import com.model.pojo.user.UserInfo;
import com.model.vo.dealer.dealerInfo.GetDealerListVO;
import com.model.vo.machine.machineInfo.getDeviceBindList.GetDeviceBindListVO;
import com.model.vo.machine.machineInfo.getMachineList.GetMachineListVO;
import com.model.vo.machine.machineInfo.importMachineInfo.ErrorMachineInfoVO;
import com.model.vo.machine.machineInfo.importMachineInfo.ImportMachineInfoVO;
import com.service.dealer.DealerInfoService;
import com.service.device.DeviceObdBaseInfoService;
import com.service.device.DevicePmdBaseInfoService;
import com.service.machine.MachineBindDeviceRecordInfoService;
import com.service.machine.MachineInfoService;
import com.service.owner.OwnerInfoService;
import com.service.sys.SysUserService;
import com.service.user.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.apache.tomcat.util.bcel.Const;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @Description
 * @Author tm
 * @Date 2023-08-26 1:19
 **/
@Api(tags = {"农机管理"})
@Slf4j
@RestController
@RequestMapping("/v1/machine")
@RequiredArgsConstructor
public class MachineInfoController {
    private final MachineInfoService machineInfoService;
    private final SysUserService sysUserService;
    private final DealerInfoService dealerInfoService;
    private final DeviceObdBaseInfoService deviceObdBaseInfoService;
    private final UserInfoService userInfoService;
    private final DevicePmdBaseInfoService devicePmdBaseInfoService;
    private final MachineBindDeviceRecordInfoService machineBindDeviceRecordInfoService;
    private final OwnerInfoService ownerInfoService;
    @Log(title = "农机管理-农机列表", businessType = BusinessType.INSERT)
    @ApiOperation(value = "农机列表")
    @PostMapping("/getMachineList")
    public Result<PageResult<List<GetMachineListVO>>> getMachineList(@RequestBody @Valid GetMachineListDTO dto) {
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        sysUser = sysUserService.get(sysUser.getSysUserId());
        List<GetMachineListVO> voList = new ArrayList<>();
        GetMachineInfoDO getMachineInfoDO = EntityConversionUtil.copy(dto, GetMachineInfoDO.class);
        if ((sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家 || sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家2) && !"testadmin".equals(sysUser.getName()) && sysUser.getUserId() != null) {
            getMachineInfoDO.setFactoryUserId(sysUser.getUserId());
        }
        if (sysUser.getUserType() == Constants.SysUserUserType.TYPE_播种机生产厂家) {
            getMachineInfoDO.setFactoryUserId(sysUser.getUserId());
        }
        if (sysUser.getUserType() == Constants.SysUserUserType.TYPE_播种机查看权限) {//播种机查看权限，查看所有播种机厂家关联的农机
            List<Long> factoryUserIds = new ArrayList<>();
            factoryUserIds.add(0l);
            GetUserInfoDO getUserInfoDO = new GetUserInfoDO();
            getUserInfoDO.setUserType(1);
            getUserInfoDO.setDeviceType(3);
            getUserInfoDO.setSortRow("id");
            List<UserInfo> userList = userInfoService.getAllList(getUserInfoDO);
            if (userList != null && userList.size() > 0) {
                factoryUserIds = userList.stream().map(UserInfo::getId).collect(Collectors.toList());
            }
            getMachineInfoDO.setFactoryUserIds(factoryUserIds);
        }
        if (sysUser.getUserType() == Constants.SysUserUserType.TYPE_播种机经销商) {
            getMachineInfoDO.setDealerUserId(sysUser.getUserId());
        }
        getMachineInfoDO.setSortRow("createTime");
        List<MachineInfo> machineList = machineInfoService.getPageList(getMachineInfoDO);
        if (machineList != null && machineList.size() > 0) {
            machineList.forEach(item -> {
                GetMachineListVO vo = EntityConversionUtil.copy(item, GetMachineListVO.class);
                vo.setMachineNo(item.getDeviceNumber());
                vo.setDtu(item.getTerminalNum());
                vo.setProduceDate(item.getProduceDate() == null ? "" : DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, item.getProduceDate()));
                String deviceType = "";
                if (item.getDeviceTypeId() == 1) deviceType = "插秧机";
                else if (item.getDeviceTypeId() == 2) deviceType = "收获机";
                else if (item.getDeviceTypeId() == 3) deviceType = "播种机";
                else if (item.getDeviceTypeId() == 4) deviceType = "植保无人飞机";
                else if (item.getDeviceTypeId() == 5) deviceType = "植保自走式地面机";
                else if (item.getDeviceTypeId() == 6) deviceType = "自走式旋耕机";
                else if (item.getDeviceTypeId() == 10) deviceType = "拖拉机";
                vo.setDeviceType(deviceType);
                String factoryName = "";
                if (item.getFactoryUserId() != null && item.getFactoryUserId() != 0) {
                    UserInfo userInfo = userInfoService.getById(item.getFactoryUserId());
                    if (userInfo != null) {
                        factoryName = userInfo.getName();
                    }
                }
                vo.setFactoryName(factoryName);
                voList.add(vo);
            });
        }
        PageInfo<MachineInfo> pageInfo = new PageInfo<>(machineList);
        PageResult<List<GetMachineListVO>> build = PageResult.<List<GetMachineListVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }

    @Log(title = "农机管理-添加和修改农机信息", businessType = BusinessType.INSERT)
    @ApiOperation(value = "添加和修改农机信息")
    @PostMapping("/saveMachineInfo")
    public Result<Objects> saveMachineInfo(@RequestBody @Valid SaveMachineInfoDTO dto) {
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        String sim = "";
        String dtu = "";
        int deviceType = 0;
        sysUser = sysUserService.get(sysUser.getSysUserId());
        if (sysUser.getUserType() == 1 || "testadmin".equals(sysUser.getName()) || sysUser.getUserId() == null) {
            return Result.fail("9999", "当前帐号不能创建农机");
        }
        UserInfo dealerInfo = null;
        if (dto.getDealerUserId() != null && dto.getDealerUserId() != 0) {
            dealerInfo = userInfoService.getById(dto.getDealerUserId());
            if (dealerInfo == null) {
                return Result.fail("9999", "经销商不存在");
            }
        }
        if (StringUtils.isNotBlank(dto.getDtu()) && sysUser.getUserId() != null && sysUser.getUserId() > 0) {
            UserInfo userInfo = userInfoService.getById(sysUser.getUserId());
            if (userInfo != null) {
                if (userInfo.getDeviceType() == 1) {
                    DeviceObdBaseInfo baseInfo = deviceObdBaseInfoService.getByDtu(dto.getDtu());
                    if (baseInfo == null) {
                        return Result.fail("9999", "终端编号不对");
                    }
                    dtu = dto.getDtu();
                    deviceType = 1;
                } else if (userInfo.getDeviceType() == 3) {
                    DevicePmdBaseInfo baseInfo = devicePmdBaseInfoService.getByDtu(dto.getDtu());
                    if (baseInfo == null) {
                        return Result.fail("9999", "终端编号不对");
                    }
                    dtu = dto.getDtu();
                    deviceType = 3;
                }
            }
        }
        if (dto.getId() != null && dto.getId() > 0) {
            MachineInfo machineInfo = machineInfoService.getById(dto.getId());
            if (machineInfo == null) {
                return Result.fail("9999", "农机不存在");
            }
            if (StringUtils.isNotBlank(dtu)) {
                GetMachineInfoDO getMachineInfoDO = new GetMachineInfoDO();
                getMachineInfoDO.setDtu(dtu);
                getMachineInfoDO.setSortRow("id");
                boolean flag = false;
                List<MachineInfo> machineList = machineInfoService.getAllList(getMachineInfoDO);
                if (machineList != null && machineList.size() > 0) {
                    for (MachineInfo info : machineList) {
                        if (info.getId() != dto.getId()) {
                            flag = true;
                            break;
                        }
                    }
                }
                if (!flag) {
                    machineInfo.setTerminalNum(dtu);
                    machineInfo.setDeviceType(deviceType);
                }
            }else{
                machineInfo.setDeviceType(0);
            }
            machineInfo.setDeviceNumber(dto.getMachineNo());
            machineInfo.setToolWidth(dto.getToolWidth());
            machineInfo.setProduceDate(DateUtils.parseStrToDate(dto.getProduceDate(), DateUtils.DATE_FORMAT_YYYY_MM_DD));
            if (dealerInfo != null) {
                machineInfo.setDealerUserId(dealerInfo.getId());
                machineInfo.setDealerName(dealerInfo.getName());
                machineInfo.setDealerPhone(dealerInfo.getCellphone());
            } else {
                machineInfo.setDealerUserId(0l);
                machineInfo.setDealerName("");
                machineInfo.setDealerPhone("");
            }
            machineInfo.setDeviceModel(dto.getDeviceModel());
            machineInfo.setDeviceTypeId(dto.getDeviceTypeId());
            machineInfo.setWarrantyType(dto.getWarrantyType());
            machineInfo.setWarrantyUnit(dto.getWarrantyUnit());
            machineInfo.setWarrantyValue(dto.getWarrantyValue());
            machineInfo.setTerminalNum(dtu);
            machineInfo.setSim(sim);
            machineInfo.setSupplierId(2l);
            machineInfo.setBlackout(1);
            machineInfoService.update(machineInfo);
        } else {
            MachineInfo machineInfo = new MachineInfo();
            if (StringUtils.isNotBlank(dtu)) {
                GetMachineInfoDO getMachineInfoDO = new GetMachineInfoDO();
                getMachineInfoDO.setDtu(dtu);
                getMachineInfoDO.setSortRow("id");
                List<MachineInfo> machineList = machineInfoService.getAllList(getMachineInfoDO);
                if (machineList != null && machineList.size() > 0) {
                    return Result.fail("9999", "该终端已被绑定");
                }
                machineInfo.setTerminalNum(dtu);
                machineInfo.setDeviceType(deviceType);
            }else{
                machineInfo.setDeviceType(0);
            }
            machineInfo.setFactoryUserId(sysUser.getUserId());
            machineInfo.setDeviceNumber(dto.getMachineNo());
            machineInfo.setToolWidth(dto.getToolWidth());
            machineInfo.setProduceDate(DateUtils.parseStrToDate(dto.getProduceDate(), DateUtils.DATE_FORMAT_YYYY_MM_DD));
            if (dealerInfo != null) {
                machineInfo.setDealerUserId(dealerInfo.getId());
                machineInfo.setDealerName(dealerInfo.getName());
                machineInfo.setDealerPhone(dealerInfo.getCellphone());
            } else {
                machineInfo.setDealerUserId(0l);
                machineInfo.setDealerName("");
                machineInfo.setDealerPhone("");
            }

            machineInfo.setDeviceModel(dto.getDeviceModel());
            machineInfo.setDeviceTypeId(dto.getDeviceTypeId());
            machineInfo.setWarrantyType(dto.getWarrantyType());
            machineInfo.setWarrantyUnit(dto.getWarrantyUnit());
            machineInfo.setWarrantyValue(dto.getWarrantyValue());
            machineInfo.setTerminalNum(dtu);
            machineInfo.setSim(sim);
            machineInfo.setIsSell(0);
            machineInfo.setSupplierId(2l);
            machineInfo.setBlackout(1);
            machineInfoService.save(machineInfo);
        }
        return Result.suc();
    }


    @Log(title = "农机管理-刪除农机信息", businessType = BusinessType.INSERT)
    @ApiOperation(value = "刪除农机信息")
    @PostMapping("/deleteMachineInfo")
    public Result<Objects> deleteMachineInfo(@RequestBody @Valid DeleteMachineInfoDTO dto) {
        MachineInfo info = machineInfoService.getById(dto.getId());
        if (info == null) {
            return Result.fail("9999", "农机不存在");
        }
        machineInfoService.delete(info);
        return Result.suc();
    }


    @Log(title = "农机管理 - 导入农机信息", businessType = BusinessType.IMPORT)
    @ApiOperation(value = "导入农机信息")
    @PostMapping(value = "/importMachineInfo")
    public Result<ImportMachineInfoVO> importMachineInfo(@RequestParam("file") MultipartFile excelFile) {
        if (StringUtils.isNull(excelFile)) {
            throw new BusinessException(ErrorCodeEnum.EXCEL_NOT_FOUNT);
        }
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        sysUser = sysUserService.get(sysUser.getSysUserId());
        List<ImportMachineInfoDTO> excelList = ExcelUtil.readExcel(excelFile, 1, 1, ImportMachineInfoDTO.class);
        if (StringUtils.isNull(excelList) || excelList.size() <= 0) {
            throw new BusinessException(ErrorCodeEnum.EXCEL_NOT_FOUNT);
        }
        List<ErrorMachineInfoVO> errorVoList = new ArrayList<>();
        //表自检
        excelList = excelList.stream().filter(o -> {
            String machineNo = Utils.verifyNullMember(o, "machineNo");
            if ("".equals(machineNo)) {
                errorVoList.add(EntityConversionUtil.copy(o, ErrorMachineInfoVO.class).errMsg("字段" + machineNo + "为空"));
                log.error("字段{}为空", machineNo);
                return false;
            }
            String dtu = Utils.verifyNullMember(o, "dtu");
            if (!"".equals(dtu)) {
                DeviceObdBaseInfo baseInfo = deviceObdBaseInfoService.getByDtu(dtu);
                if (baseInfo == null) {
                    errorVoList.add(EntityConversionUtil.copy(o, ErrorMachineInfoVO.class).errMsg("字段" + dtu + "终端不存在"));
                    log.error("字段{}终端不存在", dtu);
                    return false;
                }
                MachineInfo machineInfo = machineInfoService.getByTerminalNum(dtu);
                if (machineInfo != null) {
                    errorVoList.add(EntityConversionUtil.copy(o, ErrorMachineInfoVO.class).errMsg("字段" + dtu + "已绑定在其它农机上"));
                    log.error("字段{}已绑定在其它农机上", dtu);
                    return false;
                }
            }
            return true;
        }).collect(Collectors.toList());
        System.out.println("======导入数据条数：" + excelList.size());
        List<MachineInfo> machineList = new ArrayList<>();
        for (ImportMachineInfoDTO item : excelList) {
            MachineInfo machineInfo = new MachineInfo();
            machineInfo.setFactoryUserId(sysUser.getUserId());
            machineInfo.setDeviceNumber(item.getMachineNo());
            machineInfo.setToolWidth(item.getToolWidth());
            machineInfo.setDealerUserId(0l);
            machineInfo.setDealerName("");
            machineInfo.setDealerPhone("");
            machineInfo.setDeviceModel(item.getDeviceModel());
            int deviceTypeId = 0;
            String deviceType = item.getDeviceType();
            if ("插秧机".equals(deviceType)) deviceTypeId = 1;
            else if ("收获机".equals(deviceType)) deviceTypeId = 2;
            else if ("播种机".equals(deviceType)) deviceTypeId = 3;
            else if ("植保无人飞机".equals(deviceType)) deviceTypeId = 4;
            else if ("植保自走式地面机".equals(deviceType)) deviceTypeId = 5;
            else if ("自走式旋耕机".equals(deviceType)) deviceTypeId = 6;
            else if ("拖拉机".equals(deviceType)) deviceTypeId = 10;
            machineInfo.setDeviceTypeId(deviceTypeId);
            if ("按售后工作时长".equals(item.getWarrantyType())) machineInfo.setWarrantyType(1);
            else if ("按售后天数".equals(item.getWarrantyType())) machineInfo.setWarrantyType(2);
            if ("小时".equals(item.getWarrantyUnit())) machineInfo.setWarrantyUnit(1);
            else if ("天".equals(item.getWarrantyUnit())) machineInfo.setWarrantyUnit(2);
            else if ("月".equals(item.getWarrantyUnit())) machineInfo.setWarrantyUnit(3);
            else if ("年".equals(item.getWarrantyUnit())) machineInfo.setWarrantyUnit(4);

            machineInfo.setWarrantyValue(Integer.valueOf(item.getWarrantyValue()));
            String terminalNum = "";
            String sim = "";
            if (StringUtils.isNotBlank(item.getDtu())) {
                DeviceObdBaseInfo baseInfo = deviceObdBaseInfoService.getByDtu(item.getDtu());
                if (baseInfo != null) {
                    terminalNum = baseInfo.getDtu();
                    sim = baseInfo.getSim();
                }
            }
            machineInfo.setTerminalNum(terminalNum);
            machineInfo.setSim(sim);
            machineInfo.setIsSell(0);
            machineInfo.setSupplierId(2l);
            machineInfo.setBlackout(1);
            machineInfoService.save(machineInfo);
        }
        return Result.suc(ImportMachineInfoVO.builder().importSuccess(excelList.size()).errorList(errorVoList).build());
    }

    @Log(title = "农机管理-终端绑定解绑记录", businessType = BusinessType.SELECT)
    @ApiOperation(value = "终端绑定解绑记录")
    @PostMapping("/getDeviceBindList")
    public Result<PageResult<List<GetDeviceBindListVO>>> getDeviceBindList(@RequestBody @Valid GetDeviceBindListDTO dto) {
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        List<GetDeviceBindListVO> voList = new ArrayList<>();
        GetMachineBindDeviceRecordInfoDO getMachineBindDeviceRecordInfoDO = EntityConversionUtil.copy(dto, GetMachineBindDeviceRecordInfoDO.class);
        if (dto.getType() == 0) {
            getMachineBindDeviceRecordInfoDO.setType(null);
        }
        //农机院播种机帐号
        if ((dto.getMachineId() == null || dto.getMachineId() == 0) && sysUser.getUserType() == Constants.SysUserUserType.TYPE_播种机查看权限) {
            List<Long> machineIds = new ArrayList<>();
            machineIds.add(0l);
            GetUserInfoDO getUserInfoDO = new GetUserInfoDO();
            getUserInfoDO.setUserType(1);
            getUserInfoDO.setDeviceType(3);
            getUserInfoDO.setSortRow("id");
            List<UserInfo> userList = userInfoService.getAllList(getUserInfoDO);
            if (userList != null && userList.size() > 0) {
                List<Long> factoryUserIds = userList.stream().map(UserInfo::getId).collect(Collectors.toList());
                GetMachineInfoDO getMachineInfoDO = new GetMachineInfoDO();
                getMachineInfoDO.setFactoryUserIds(factoryUserIds);
                getMachineInfoDO.setSortRow("id");
                List<MachineInfo> machineList = machineInfoService.getAllList(getMachineInfoDO);
                if (machineList != null && machineList.size() > 0) {
                    machineIds = machineList.stream().map(MachineInfo::getId).collect(Collectors.toList());
                }
            }
            getMachineBindDeviceRecordInfoDO.setMachineIds(machineIds);
        }
        //播种机厂家 播种机经销商
        if (sysUser.getUserType() == Constants.SysUserUserType.TYPE_播种机生产厂家 || sysUser.getUserType() == Constants.SysUserUserType.TYPE_播种机经销商) {
            List<Long> machineIds = new ArrayList<>();
            machineIds.add(0l);
            GetMachineInfoDO getMachineInfoDO = new GetMachineInfoDO();
            if (sysUser.getUserType() == Constants.SysUserUserType.TYPE_播种机生产厂家)
                getMachineInfoDO.setFactoryUserId(sysUser.getUserId());
            else if (sysUser.getUserType() == Constants.SysUserUserType.TYPE_播种机经销商)
                getMachineInfoDO.setDealerUserId(sysUser.getUserId());
            getMachineInfoDO.setSortRow("id");
            List<MachineInfo> machineList = machineInfoService.getAllList(getMachineInfoDO);
            if (machineList != null && machineList.size() > 0) {
                machineIds = machineList.stream().map(MachineInfo::getId).collect(Collectors.toList());
            }
            getMachineBindDeviceRecordInfoDO.setMachineIds(machineIds);
        }
        getMachineBindDeviceRecordInfoDO.setSortRow("createTime");
        List<MachineBindDeviceRecordInfo> bindList = machineBindDeviceRecordInfoService.getPageList(getMachineBindDeviceRecordInfoDO);
        if (bindList != null && bindList.size() > 0) {
            Map<Long, String> map = new HashMap<>();
            bindList.forEach(item -> {
                GetDeviceBindListVO vo = EntityConversionUtil.copy(item, GetDeviceBindListVO.class);
                String machineName = "";
                MachineInfo machineInfo = machineInfoService.getById(item.getMachineId());
                if (machineInfo != null) {
                    if (machineInfo.getDeviceNumber() != null) machineName += machineInfo.getDeviceNumber();
                    if (machineInfo.getDeviceModel() != null) machineName += machineInfo.getDeviceModel();
                }
                vo.setMachineName(machineName);
                String factoryName = "";
                if (item.getFactoryUserId() != null && item.getFactoryUserId() != 0) {
                    if (map.get(item.getFactoryUserId()) != null) {
                        factoryName = map.get(item.getFactoryUserId());
                    } else {
                        UserInfo userInfo = userInfoService.getById(item.getFactoryUserId());
                        if (userInfo != null) {
                            factoryName = userInfo.getName();
                        }
                    }
                }
                vo.setFactoryName(factoryName);
                voList.add(vo);
            });
        }
        PageInfo<MachineBindDeviceRecordInfo> pageInfo = new PageInfo<>(bindList);
        PageResult<List<GetDeviceBindListVO>> build = PageResult.<List<GetDeviceBindListVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }

    @Log(title = "农机管理-绑定解绑终端", businessType = BusinessType.INSERT)
    @ApiOperation(value = "绑定解绑终端")
    @PostMapping("/bindDeviceInfo")
    public Result<Objects> bindDeviceInfo(@RequestBody @Valid BindDeviceInfoDTO dto) {
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        int deviceType = 0;
        switch (sysUser.getUserType()) {
            case Constants.SysUserUserType.TYPE_TBOX生产厂家:
            case Constants.SysUserUserType.TYPE_TBOX生产厂家2:
            case Constants.SysUserUserType.TYPE_TBOX经销商:
                deviceType = Constants.DeviceType.TYPE_TBOX;
                break;
            case Constants.SysUserUserType.TYPE_播种机生产厂家:
            case Constants.SysUserUserType.TYPE_播种机经销商:
                deviceType = Constants.DeviceType.TYPE_播种机;
                break;
            default:
                break;

        }
        MachineInfo machineInfo = machineInfoService.getById(dto.getMachineId());
        if (machineInfo == null) {
            return Result.fail("9999", "农机不存在");
        }
        if (dto.getType() == 2 && StringUtils.isBlank(machineInfo.getTerminalNum())) {
            return Result.fail("9999", "该农机未绑定终端");
        }
        if (dto.getType() == 1 && StringUtils.isNotBlank(machineInfo.getTerminalNum())) {
            return Result.fail("9999", "该农机已绑定终端");
        }
        int num = 0;
        if (dto.getType() == 1) {
            DevicePmdBaseInfo baseInfo = devicePmdBaseInfoService.getByDtu(dto.getDtu());
            if (baseInfo == null) {
                return Result.fail("9999", "该终端不存在");
            }
            GetMachineInfoDO getMachineInfoDO = new GetMachineInfoDO();
            getMachineInfoDO.setTerminalNum(dto.getDtu());
            getMachineInfoDO.setSortRow("id");
            List<MachineInfo> machineList = machineInfoService.getAllList(getMachineInfoDO);
            if (machineList != null && machineList.size() > 0) {
                return Result.fail("9999", "该终端已被绑定");
            }
            machineInfo.setTerminalNum(dto.getDtu());
            machineInfo.setDeviceType(deviceType);
            num = machineInfoService.update(machineInfo);
        } else if (dto.getType() == 2) {
            machineInfo.setTerminalNum("");
            machineInfo.setDeviceType(0);
            num = machineInfoService.update(machineInfo);
        }


        if (num > 0) {
            MachineBindDeviceRecordInfo recordInfo = new MachineBindDeviceRecordInfo();
            recordInfo.setFactoryUserId(sysUser.getUserId());
            recordInfo.setDtu(dto.getDtu());
            recordInfo.setMachineId(machineInfo.getId());
            recordInfo.setType(dto.getType());
            machineBindDeviceRecordInfoService.save(recordInfo);
        }
        return Result.suc();
    }

    /*@Log(title = "农机管理-绑定解绑终端", businessType = BusinessType.INSERT)
    @ApiOperation(value = "绑定解绑终端")
    @PostMapping("/bindDeviceInfo")
    public Result<Objects> bindDeviceInfo(@RequestBody @Valid BindDeviceInfoDTO dto) {

    }*/

    @Log(title = "农机管理-绑定经销商", businessType = BusinessType.INSERT)
    @ApiOperation(value = "绑定经销商")
    @PostMapping("/bindDealerInfo")
    public Result<Objects> bindDealerInfo(@RequestBody @Valid BindDealerInfoDTO dto) {
        MachineInfo machineInfo = machineInfoService.getById(dto.getMachineId());
        if (machineInfo == null) {
            return Result.fail("9999", "农机不存在");
        }
        if (machineInfo.getDealerUserId() != null && machineInfo.getDealerUserId() > 0) {
            return Result.fail("9999", "该农机已经绑定经销商");
        }
        UserInfo userInfo = userInfoService.getById(dto.getDealerUserId());
        if (userInfo == null) {
            return Result.fail("9999", "该经销商不存在");
        }
        machineInfo.setDealerUserId(userInfo.getId());
        machineInfo.setDealerPhone(userInfo.getCellphone());
        machineInfo.setDealerName(userInfo.getName());
        machineInfoService.update(machineInfo);
        return Result.suc();
    }

    @Log(title = "农机管理-绑定农户", businessType = BusinessType.INSERT)
    @ApiOperation(value = "绑定农户")
    @PostMapping("/bindOwnerInfo")
    public Result<Objects> bindOwnerInfo(@RequestBody @Valid BindOwnerInfoDTO dto) {
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        int deviceType = 1;
        if (sysUser.getUserType() == Constants.SysUserUserType.TYPE_播种机经销商) {
            deviceType = 3;
        }
        MachineInfo machineInfo = machineInfoService.getById(dto.getMachineId());
        if (machineInfo == null) {
            return Result.fail("9999", "农机不存在");
        }
        if (machineInfo.getOwnerUserId() != null && machineInfo.getOwnerUserId() > 0) {
            return Result.fail("9999", "该农机已经绑定农户");
        }
        UserInfo userInfo = userInfoService.getByCellphone(dto.getCellphone());
        if (userInfo != null) {
            machineInfo.setOwnerUserId(userInfo.getId());
            machineInfo.setOwnerPhone(userInfo.getCellphone());
            machineInfo.setOwnerName(userInfo.getName());
            machineInfo.setSellTime(new Date());
            machineInfo.setIsSell(1);
            machineInfoService.update(machineInfo);
        } else {
            userInfo = new UserInfo();
            userInfo.setName(dto.getOwnerName());
            String password = dto.getCellphone().substring(dto.getCellphone().length() - 6, dto.getCellphone().length());
            userInfo.setPassword(MD5.encode(password, "utf-8"));
            userInfo.setCellphone(dto.getCellphone());
            userInfo.setUserType(3);
            userInfo.setAllowSecondSupply(0);
            userInfo.setCompanyName("");
            userInfo.setCompanyCode("");
            userInfo.setLicenseUrl("");
            userInfo.setFileUrls("");
            userInfo.setForwardAccount("");
            userInfo.setForwardPwd("");
            userInfo.setDeviceType(deviceType);
            userInfo = userInfoService.save(userInfo);
            if (userInfo.getId() > 0) {
                machineInfo.setOwnerUserId(userInfo.getId());
                machineInfo.setOwnerPhone(userInfo.getCellphone());
                machineInfo.setOwnerName(userInfo.getName());
                machineInfo.setSellTime(new Date());
                machineInfo.setIsSell(1);
                machineInfoService.update(machineInfo);
            }
        }
        if(userInfo!=null && userInfo.getId()>0){
            OwnerInfo ownerInfo = ownerInfoService.findByDealerAndOwner(sysUser.getUserId(),userInfo.getId());
            if(ownerInfo == null){
                ownerInfo = new OwnerInfo();
                ownerInfo.setDealerUserId(sysUser.getUserId());
                ownerInfo.setOwnerName(userInfo.getName());
                ownerInfo.setOwnerPhone(userInfo.getCellphone());
                ownerInfo.setOwnerUserId(userInfo.getId());
                ownerInfoService.save(ownerInfo);
            }
        }
        return Result.suc();
    }


    /*@Log(title = "农机管理 - 导入农机信息", businessType = BusinessType.IMPORT)
    @ApiOperation(value = "导入农机信息")
    @PostMapping(value = "/importMachineInfo")
    public Result<ImportLandInfoVO> importMachineInfo(@RequestParam("file") MultipartFile excelFile) {
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SystemPortalAdministrator user = systemPortalAdministratorService.getById(loginUserDetails.getUser().getId());
        if (StringUtils.isNull(excelFile)) {
            throw new BusinessException(ErrorCodeEnum.EXCEL_NOT_FOUNT);
        }
        List<ImportLandInfoDTO> excelList = ExcelUtil.readExcel(excelFile, 1, 1, ImportLandInfoDTO.class);
        if (StringUtils.isNull(excelList) || excelList.size() <= 0) {
            throw new BusinessException(ErrorCodeEnum.EXCEL_NOT_FOUNT);
        }
        List<ErrorLandInfoVO> errorVoList = new ArrayList<>();

        //表自检
        excelList = excelList.stream().filter(o -> {
            String landNo = Utils.verifyNullMember(o, "landNo");
            if (!"".equals(landNo)) {
                errorVoList.add(EntityConversionUtil.copy(o, ErrorLandInfoVO.class).errMsg("字段" + landNo + "为空"));
                log.error("字段{}为空", landNo);
                return false;
            }
            String landName = Utils.verifyNullMember(o,"landName");
            if (!"".equals(landName)) {
                errorVoList.add(EntityConversionUtil.copy(o, ErrorLandInfoVO.class).errMsg("字段" + landName + "为空"));
                log.error("字段{}为空", landNo);
                return false;
            }
            return true;
        }).collect(Collectors.toList());
        List<LandInfo> landList = new ArrayList<>();
        excelList.forEach(item->{
            LandInfo landInfo = EntityConversionUtil.copy(item,LandInfo.class);
            landInfo.setTotalArea(item.getArea());
            landInfo.setOrgId(user.getOrgId());
            landInfo.setCreatedTime(new Date());
            landList.add(landInfo);
        });
        landInfoService.saveList(landList);
        return Result.suc(ImportLandInfoVO.builder().importSuccess(excelList.size()).errorList(errorVoList).build());
    }*/
}
